<?php
class Pager
{
	private $mapper = null;
	private $requete = null;
	private $nbpages = 0;
	private $nbparpages = 0;
	private $nbtotal = 0;
	private $pageactuelle = 0;
	
	public function __construct(Model_IMapper $mapper, $nbpage, $total)
	{
		$this->mapper = $mapper;
		$this->nbparpages = $nbpage;
		$this->nbtotal = $total;
		$this->nbpages = ceil($this->nbtotal / $this->nbparpages);
	}
	
	public function init()
	{
		if( isset($_GET['page']) && is_numeric($_GET['page']))
		{
			$this->pageactuelle = intval($_GET['page']);
			
			if($this->pageactuelle > $this->nbpages)
			{
				$this->pageactuelle = $this->nbpages;
			}
		}
		else
		{
			$this->pageactuelle = 1;
		}
	}
	
	public function setQuery($req)
	{
		$this->requete = $req;
	}
	
	public function haveToPaginate()
	{
		if($this->nbtotal <= $this->nbparpages)
		{
			return false;
		}
		else
		{
			return true;
		}		
	}
	
	public function getPage()
	{
		return $this->pageactuelle;
	}
	
	public function getLastPage()
	{
		return $this->nbpages;
	}
	
	public function getPreviousPage()
	{
		$p = $this->pageactuelle - 1;
		if($p < 1)
		{
			$p = 1;
		}
		return $p;
	}
	
	public function getNextPage()
	{
		$p = $this->pageactuelle + 1;
		if($p > $this->nbpages)
		{
			$p = $this->nbpages;
		}
		return $p;
	}
	
	public function getResults()
	{
		$nbdepart = ($this->pageactuelle - 1) * $this->nbparpages;
		$nbaffiche = $this->nbparpages;
		$results = call_user_func(array($this->mapper, $this->requete), $nbdepart, $nbaffiche);
		return $results;
	}
	
	public function getLinks()
	{
		$pages = array();
		for($i=1; $i <= $this->nbpages; $i++)
		{
			$pages[] = $i;
		}
		
		return $pages;
	}
}